#include "AudioInput.h"
#include <QDebug>

#include "MessageHelper.h"

extern MsgQueue queue_send;

AudioInput::AudioInput(QObject* parent)
    : QObject(parent),
      m_audioInput(nullptr),
      m_inputDevice(nullptr)
{
    QAudioFormat format;
    format.setSampleRate(16000);  // 16kHz
    format.setChannelCount(1);    // Mono
    format.setSampleSize(16);     // 16-bit
    format.setCodec("audio/pcm");
    format.setByteOrder(QAudioFormat::LittleEndian);
    format.setSampleType(QAudioFormat::SignedInt);

    QAudioDeviceInfo info = QAudioDeviceInfo::defaultInputDevice();
    if (!info.isFormatSupported(format)) {
        qWarning() << "默认输入设备不支持，使用最接近的格式";
        format = info.nearestFormat(format);
    }

    m_audioInput = new QAudioInput(info, format, this);

    // 设置低延迟缓冲（约100ms）
    m_audioInput->setBufferSize(3200);
}

AudioInput::~AudioInput()
{
    stop();
}

void AudioInput::start()
{
    if (!m_audioInput) return;
    m_inputDevice = m_audioInput->start();
    //connect(m_inputDevice, &QIODevice::readyRead, this, &AudioInput::handleReadyRead);
}

void AudioInput::stop()
{
    if (m_audioInput) {
        m_audioInput->stop();
        m_inputDevice = nullptr;
    }
}

void AudioInput::handleReadyRead()
{
    if (!m_inputDevice) return;
    QByteArray data = m_inputDevice->readAll();
    if (!data.isEmpty()) {
        queue_send.push_back(MessageHelper::makeMediaMessage(data, MSG::Type::AUDIO));
    }
}
